import { login, getUserBaseInfo, getEmployeeBaseInfo } from '@/api/user'
import router from '../../router'
import {
  getToken,
  setToken,
  removeToken,
  getUserInfo,
  setUserInfo,
  removeUserInfo
} from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from 'element-ui'
import { asyncRoutes } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: getUserInfo() || {}
  },
  mutations: {
    // 登录
    login(state, token) {
      state.token = token
      setToken(token)
    },
    // 退出登录
    logout(state) {
      state.token = ''
      state.userInfo = {}
      removeToken() // 移除token
      removeUserInfo() // 移除用户资料
      resetRouter() // 重置路由
    },
    // 获取用户基本资料
    getUserBaseInfo(state, payload) {
      state.userInfo = payload
      setUserInfo(payload)
    }
  },
  actions: {
    // 登录
    async asyncLogin(context, data) {
      const res = await login(data)
      context.commit('login', res)
    },
    // 获取用户基本资料
    async asyncGetUserBaseInfo(context) {
      try {
        const res = await getUserBaseInfo()
        const res1 = await getEmployeeBaseInfo(res.userId)
        Message('获取用户资料成功')
        context.commit('getUserBaseInfo', { ...res, ...res1 })
        // 添加路由权限
        const {
          roles: { menus }
        } = { ...res, ...res1 }
        const routes = asyncRoutes.filter((item) =>
          menus.some((key) => key === item.name)
        )
        router.addRoutes([
          // ...asyncRoutes, 调试时把这个打开下面关闭
          ...routes,
          { path: '*', redirect: '/404', hidden: true }
        ])
        // 为左侧菜单栏添加数据
        context.commit('permission/setRoutes', routes, { root: true })
      } catch (err) {
        Message('获取用户资料失败')
      }
    }
  }
}
